package cz.fimuni.pa165.backendderby.dao;

import cz.fimuni.pa165.backendderby.entities.Company;
import cz.fimuni.pa165.backendderby.entities.Employee;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Michal Polkorab
 */
@Repository
public class EmployeeDAOImpl implements EmployeeDAO{

    @PersistenceContext
    private EntityManager em;

  
    @Override
    public void create(Employee employee) {
        if (employee != null){
            em.persist(employee);
        }      
    }

    @Override
    public Employee get(Long id) {
        if (id == null){
            return null;
        }
        Employee employee = em.find(Employee.class, id);
        return employee;
    }

    @Override
    public boolean update(Employee employee) {
        if (employee != null){
            if (em.find(Employee.class, employee.getId()) == null)
              {return false;}
            em.persist(em.merge(employee));
            return true;
        }
        return false;
    }

    @Override
    public void remove(Employee employee) {
        if (employee != null){
            Employee employeefound = em.find(Employee.class, employee.getId());
            if (employeefound != null){
                em.remove(employeefound);
            }
        }  
    }
    
    public List<Employee> getAllEmployees() {
        Query q = em.createQuery("SELECT e FROM Employee e");
        List<Employee> result = q.getResultList();
        return result;
    }

    public List<Employee> findByName(String surname) {
        Query q = em.createQuery("SELECT e FROM Employee e WHERE e.surname= :emp");
        q.setParameter("emp", surname);
        List<Employee> result = q.getResultList();
        return result;
    }
    
    public List<Employee> findByUsername(String username) {
        Query q = em.createQuery("SELECT e FROM Employee e WHERE e.username= :emp");
        q.setParameter("emp", username);
        List<Employee> result = q.getResultList();
        return result;
    }

    public List<Employee> findByCompany(Company company) {
        Query q = em.createQuery("SELECT e FROM Employee e WHERE e.company= :emp");
        q.setParameter("emp", company);
        List<Employee> result = q.getResultList();
        return result;
    }
    
}
